#include <liblut/algo/convert2img.hpp>

using namespace boost;

void
convert2img(boost::shared_ptr<LutModel> plut, gil::rgb8_view_t& output)
{
    //----- coordinate transform from Attribut space to output image space
    double minAttSpace=plut->begin()->getValue();
    double maxAttSpace=plut->rbegin()->getValue();
    double scale=(static_cast<double>
                  (output.width()))/(maxAttSpace-minAttSpace);
    double offset=(0 - scale*minAttSpace);
    double rscale=(maxAttSpace-minAttSpace)/
            (static_cast<double> (output.width()));
    double roffset=(minAttSpace - rscale*0);

    //------- interpole first line
    BoundInterpolator interpolator=plut->getInterpolator();
    LutModel::iterator BoundInf=plut->begin();
    LutModel::iterator BoundSup=++(plut->begin());
    //TODO use gil pixel horizontal iterator
    for (int x=0; x<output.width(); x++)
    {
        double xAtt=roffset + x*rscale;
        LutColor tempLutColor = interpolator.interpole(*BoundInf,
                                                       *BoundSup,
                                                       xAtt);
        LutColor tempRVBColor=tempLutColor.toRGB();
        output(x,0)=gil::rgb8_pixel_t(
                    static_cast<unsigned char>(tempRVBColor.getC1()),
                    static_cast<unsigned char>(tempRVBColor.getC2()),
                    static_cast<unsigned char>(tempRVBColor.getC3())
                   );

        if( (xAtt+rscale)>= BoundSup->getValue() )
        {
          BoundInf++;
          BoundSup++;
        }
    }

   //----------------------------------
   //fill other line by copying first line
    for (int y=1; y<output.height(); y++)
    {
        for (int x=0; x<output.width(); x++)
        {
            output(x,y)=output(x,0);
        }
    }

}
